package com.jianjian.system.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jianjian.model.system.SysRole;
import com.jianjian.model.system.SysUserRole;
import com.jianjian.model.vo.AssginRoleVo;
import com.jianjian.model.vo.SysRoleQueryVo;
import com.jianjian.system.mapper.SysRoleMapper;
import com.jianjian.system.mapper.SysUserRoleMapper;
import com.jianjian.system.service.SysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Zsir
 * @create 2022-10-26 15:36
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper,SysRole> implements SysRoleService {

    //中间表
    @Autowired
    private SysUserRoleMapper userRoleMapper;

    //条件分页查询
    @Override
    public IPage<SysRole> selectPage(Page<SysRole> pageParam, SysRoleQueryVo sysRoleQueryVo) {

        /*
      if (StringUtils.isEmpty(sysRoleQueryVo.getRoleName())){
          return  baseMapper.selectPage(pageParam,null);
      }

      QueryWrapper<SysRole> wrapper = new QueryWrapper<>();
      wrapper.like("role_name",sysRoleQueryVo.getRoleName());
      wrapper.orderByDesc("id");
      return  baseMapper.selectPage(pageParam,wrapper);
      */

       return baseMapper.selectPage(pageParam,sysRoleQueryVo);
    }

    //根据用户获取角色数据
    @Override
    public Map<String, Object> getRolesByUserId(Long userId) {
        //获取所有角色
        List<SysRole> roleList = this.list();
        //根据用户id查询,已经分配角色信息
        QueryWrapper<SysUserRole> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId);
        List<SysUserRole> userRoles = userRoleMapper.selectList(wrapper);
      List<String> ids =   userRoles.stream().map(userRole ->{
            return userRole.getRoleId();
        }).collect(Collectors.toList());
       Map<String,Object> map = new HashMap<>();
       map.put("allRoles",roleList);
       map.put("userRoleIds",ids);
        return map;
    }

    //用户重新分配角色
    @Override
    public void doAssign(AssginRoleVo assginRoleVo) {
        //删除用户之前的角色
        QueryWrapper<SysUserRole> wrapper =  new QueryWrapper<>();
       userRoleMapper.delete(wrapper.eq("user_id",assginRoleVo.getUserId()));
       //重新为用户添加角色
        List<String> roleIdList = assginRoleVo.getRoleIdList();
        roleIdList.forEach(roleId ->{
            userRoleMapper.insert(new SysUserRole(roleId,assginRoleVo.getUserId()));
        });
    }


}
